package com.study.mike;


import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author KangHui
 * @Date 2023/8/31 14:39
 */
@Slf4j
public class PdfTOPang {
    public static void main(String[] args) throws IOException {
        doTestFile("快递鸟接口技术文档v5.PDF",
                "C:\\Users\\James\\Desktop", "C:\\Users\\James\\Desktop\\images");

    }

    public static boolean doTestFile(String fileName, String inDir, String outDir) throws IOException {

        PDDocument document = null;
        long generateStart = System.currentTimeMillis();
        try {


            //加载PDF 文件
            document = Loader.loadPDF(new File(inDir + '/' + fileName), (String) null);

            //生成前缀
            String outputPrefix = outDir + '/' + fileName + "-";

            //获取 PDF 页数
            int numPages = document.getNumberOfPages();

            //当 PDF 页数 小于 1
            if (numPages < 1) {
                throw new IOException("PDF 页数小于 1");
            }

            PDFRenderer renderer = new PDFRenderer(document);
            //循环处理每页 PDF
            for (int i = 0; i < numPages; i++) {
                //创建 PNG 名称
                String pngFileName = outputPrefix + (i + 1) + ".png";
                //将对应 PDF 页面转成 Image 对象、图像 DPI
                BufferedImage image = renderer.renderImageWithDPI(i, 200);
                //输出图片
                ImageIO.write(image, "PNG", new File(pngFileName));

            }

        } catch (IOException e) {
            throw e;
        } finally {
            if (document != null) {
                document.close();
            }
        }
        long generateEnd = System.currentTimeMillis();
        log.info("合同生成耗时(秒)：" + (generateEnd - generateStart) / 1000);
        return false;
    }

}
